/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.vo.ClazzanddepartmentQueryCriteria;
import me.zhengjie.modules.system.mapper.*;
import me.zhengjie.modules.system.service.ClazzanddepartmentService;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.utils.PageUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.Authentication;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
* @description 服务实现
* @author shitou
* @date 2025-02-02
**/
@Service
@RequiredArgsConstructor
public class ClazzanddepartmentServiceImpl extends ServiceImpl<ClazzanddepartmentMapper, Clazzanddepartment> implements ClazzanddepartmentService {

    private final ClazzanddepartmentMapper clazzanddepartmentMapper;

    private final ClazzMapper clazzMapper;

    private final DepartmentteacherMapper departmentteacherMapper;

    private final TeacherMapper teacherMapper;

    private final UserMapper userMapper;

    private final ClazzandteacherMapper clazzandteacherMapper;

    private final ClazzandstudentMapper clazzandstudentMapper;

    private final ClazzandteskMapper clazzandteskMapper;

    private final ClazzteachMapper clazzteachMapper;

    private final ClazzcourseMapper clazzcourseMapper;


    @Override
    public PageResult<Clazzanddepartment> queryAll(ClazzanddepartmentQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(clazzanddepartmentMapper.findAll(criteria, page));
    }

    @Override
    public Map<String,Object> queryClazzOtherNum(ClazzanddepartmentQueryCriteria criteria){
//根据班级班级查询 学生 教师 课程 任务 教材
        List<Clazzandstudent> clazzandstudentList = new ArrayList<>();
        List<Clazzandteacher> clazzandteacherList = new ArrayList<>();
        List<Clazzandtesk> clazzandteskList = new ArrayList<>();
        List<Clazzcourse> clazzcourseList = new ArrayList<>();
        List<Clazzteach> clazzteachList = new ArrayList<>();

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("clazzId",criteria.getClazzId());
        clazzandstudentList = clazzandstudentMapper.selectList(queryWrapper2);

        QueryWrapper queryWrapper3 = new QueryWrapper<>();
        queryWrapper3.eq("clazzId",criteria.getClazzId());
        clazzandteacherList = clazzandteacherMapper.selectList(queryWrapper3);

        QueryWrapper queryWrapper4 = new QueryWrapper<>();
        queryWrapper4.eq("clazzId",criteria.getClazzId());
        clazzandteskList = clazzandteskMapper.selectList(queryWrapper4);

        QueryWrapper queryWrapper5 = new QueryWrapper<>();
        queryWrapper5.eq("clazzId",criteria.getClazzId());
        clazzcourseList = clazzcourseMapper.selectList(queryWrapper5);

        QueryWrapper queryWrapper6 = new QueryWrapper<>();
        queryWrapper6.in("clazzId",criteria.getClazzId());
        clazzteachList = clazzteachMapper.selectList(queryWrapper6);

        Map<String,Object> map = new HashMap<>();
        map.put("studentNum",clazzandstudentList.size());
        map.put("teacherNum",clazzandteacherList.size());
        map.put("teskNum",clazzandteskList.size());
        map.put("courseNum",clazzcourseList.size());
        map.put("teachNum",clazzteachList.size());
        return map;
    }

    @Override
    public List<Map<String,Object>> queryClazzanddepartment(ClazzanddepartmentQueryCriteria criteria){

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapperTeacher = new QueryWrapper<>();
        queryWrapperTeacher.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapperTeacher);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teacherId",teacher.getId());
        Departmentteacher departmentteacher = departmentteacherMapper.selectOne(queryWrapper1);
        criteria.setDepartmentId(departmentteacher.getDepartmentId());

        List<Clazzanddepartment> clazzanddepartmentList = clazzanddepartmentMapper.findAll(criteria);
        List<Integer> clazzIds = new ArrayList<>();
        for(Clazzanddepartment clazzanddepartment:clazzanddepartmentList){
            clazzIds.add(clazzanddepartment.getClazzId());
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",clazzIds);
        queryWrapper.eq("status",1);
        if(criteria.getName() !=null){
            queryWrapper.like("name",criteria.getName());
        }
        List<Clazz> clazzList = new ArrayList<>();
        if(clazzIds.size()!=0){
            clazzList = clazzMapper.selectList(queryWrapper);
        }
        List<Map<String,Object>> clazzMapList = new ArrayList<>();

        //根据班级班级查询 学生 教师 课程 任务 教材
        List<Clazzandstudent> clazzandstudentList = new ArrayList<>();
        List<Clazzandteacher> clazzandteacherList = new ArrayList<>();
        List<Clazzandtesk> clazzandteskList = new ArrayList<>();
        List<Clazzcourse> clazzcourseList = new ArrayList<>();
        List<Clazzteach> clazzteachList = new ArrayList<>();
        if(clazzIds.size()!=0){
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("clazzId",clazzIds);
            clazzandstudentList = clazzandstudentMapper.selectList(queryWrapper2);

            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("clazzId",clazzIds);
            clazzandteacherList = clazzandteacherMapper.selectList(queryWrapper3);

            QueryWrapper queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.in("clazzId",clazzIds);
            clazzandteskList = clazzandteskMapper.selectList(queryWrapper4);

            QueryWrapper queryWrapper5 = new QueryWrapper<>();
            queryWrapper5.in("clazzId",clazzIds);
            clazzcourseList = clazzcourseMapper.selectList(queryWrapper5);

            QueryWrapper queryWrapper6 = new QueryWrapper<>();
            queryWrapper6.in("clazzId",clazzIds);
            clazzteachList = clazzteachMapper.selectList(queryWrapper6);
        }
        for(Clazz clazz:clazzList){

            Map<String,Object> map = new HashMap<>();
            map.put("id",clazz.getId());
            map.put("name",clazz.getName());
            map.put("info",clazz.getInfo());
            map.put("schoolId",clazz.getSchoolid());
            map.put("studentNum",0);
            map.put("teachNum",0);
            map.put("courseNum",0);
            map.put("testNum",0);

            for(Clazzandstudent clazzandstudent:clazzandstudentList){
                if(clazzandstudent.getClazzId() == clazz.getId()){
                    map.put("studentNum",(Integer )map.get("studentNum") + 1);
                }
            }

            for(Clazzandtesk clazzandtesk:clazzandteskList){
                if(Math.toIntExact(clazzandtesk.getClazzid()) == clazz.getId()){
                    map.put("testNum",(Integer )map.get("testNum") + 1);
                }
            }

            for(Clazzcourse clazzcourse:clazzcourseList){
                if(Math.toIntExact(clazzcourse.getClazzid()) == clazz.getId()){
                    map.put("courseNum",(Integer )map.get("courseNum") + 1);
                }
            }

            for(Clazzteach clazzteach:clazzteachList){
                if(Math.toIntExact(clazzteach.getClazzId()) == clazz.getId()){
                    map.put("teachNum",(Integer )map.get("teachNum") + 1);
                }
            }
            clazzMapList.add(map);
        }
        return clazzMapList;
    }
    public List<Map<String,Object>> queryTeacherClazz(ClazzanddepartmentQueryCriteria criteria){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapperTeacher = new QueryWrapper<>();
        queryWrapperTeacher.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapperTeacher);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teacherId",teacher.getId());
        List<Clazzandteacher> cuclazzandteacherList = clazzandteacherMapper.selectList(queryWrapper1);


        List<Integer> clazzIds = new ArrayList<>();
        for(Clazzandteacher clazzanddepartment:cuclazzandteacherList){
            clazzIds.add(clazzanddepartment.getClazzId());
        }
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",clazzIds);
        queryWrapper.eq("status",1);
        if(criteria.getName()!=null){
            queryWrapper.like("name",criteria.getName());
        }

        List<Clazz> clazzList = new ArrayList<>();
        if(clazzIds.size()!=0){
            clazzList = clazzMapper.selectList(queryWrapper);
        }
        List<Map<String,Object>> clazzMapList = new ArrayList<>();

        //根据班级班级查询 学生 教师 课程 任务 教材
        List<Clazzandstudent> clazzandstudentList = new ArrayList<>();
        List<Clazzandteacher> clazzandteacherList = new ArrayList<>();
        List<Clazzandtesk> clazzandteskList = new ArrayList<>();
        List<Clazzcourse> clazzcourseList = new ArrayList<>();
        List<Clazzteach> clazzteachList = new ArrayList<>();
        if(clazzIds.size()!=0){
            QueryWrapper queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.in("clazzId",clazzIds);
            clazzandstudentList = clazzandstudentMapper.selectList(queryWrapper2);

            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("clazzId",clazzIds);
            clazzandteacherList = clazzandteacherMapper.selectList(queryWrapper3);

            QueryWrapper queryWrapper4 = new QueryWrapper<>();
            queryWrapper4.in("clazzId",clazzIds);
            clazzandteskList = clazzandteskMapper.selectList(queryWrapper4);

            QueryWrapper queryWrapper5 = new QueryWrapper<>();
            queryWrapper5.in("clazzId",clazzIds);
            clazzcourseList = clazzcourseMapper.selectList(queryWrapper5);

            QueryWrapper queryWrapper6 = new QueryWrapper<>();
            queryWrapper6.in("clazzId",clazzIds);
            clazzteachList = clazzteachMapper.selectList(queryWrapper6);
        }
        for(Clazz clazz:clazzList){

            Map<String,Object> map = new HashMap<>();
            map.put("id",clazz.getId());
            map.put("name",clazz.getName());
            map.put("info",clazz.getInfo());
            map.put("schoolId",clazz.getSchoolid());
            map.put("studentNum",0);
            map.put("teachNum",0);
            map.put("courseNum",0);
            map.put("testNum",0);

            for(Clazzandstudent clazzandstudent:clazzandstudentList){
                if(clazzandstudent.getClazzId() == clazz.getId()){
                    map.put("studentNum",(Integer )map.get("studentNum") + 1);
                }
            }

            for(Clazzandtesk clazzandtesk:clazzandteskList){
                if(Math.toIntExact(clazzandtesk.getClazzid()) == clazz.getId()){
                    map.put("testNum",(Integer )map.get("testNum") + 1);
                }
            }

            for(Clazzcourse clazzcourse:clazzcourseList){
                if(Math.toIntExact(clazzcourse.getClazzid()) == clazz.getId()){
                    map.put("courseNum",(Integer )map.get("courseNum") + 1);
                }
            }

            for(Clazzteach clazzteach:clazzteachList){
                if(Math.toIntExact(clazzteach.getClazzId()) == clazz.getId()){
                    map.put("teachNum",(Integer )map.get("teachNum") + 1);
                }
            }
            clazzMapList.add(map);
        }
        return clazzMapList;
    }
    @Override
    public List<Clazzanddepartment> queryAll(ClazzanddepartmentQueryCriteria criteria){
        return clazzanddepartmentMapper.findAll(criteria);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(Clazz clazz) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String currentUserName = authentication.getName();
        User currentUser = userMapper.findByUsername(currentUserName);

        QueryWrapper queryWrapperTeacher = new QueryWrapper<>();
        queryWrapperTeacher.eq("userId",currentUser.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapperTeacher);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teacherId",teacher.getId());
        Departmentteacher departmentteacher = departmentteacherMapper.selectOne(queryWrapper1);

        clazzMapper.insert(clazz);
        Clazzanddepartment clazzanddepartment = new Clazzanddepartment();
        clazzanddepartment.setClazzId(Math.toIntExact(clazz.getId()));
        clazzanddepartment.setDepartmentId(departmentteacher.getDepartmentId());
        save(clazzanddepartment);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Clazz resources) {
        Clazz clazzanddepartment = clazzMapper.selectById(resources.getId());
        clazzanddepartment.copy(resources);
//        saveOrUpdate(clazzanddepartment);
        clazzMapper.updateById(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<Clazzanddepartment> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (Clazzanddepartment clazzanddepartment : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put(" clazzid",  clazzanddepartment.getClazzId());
            map.put(" dempartmentid",  clazzanddepartment.getDepartmentId());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}